package com.whut.whw.main;

import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;


import com.whut.whw.R;
import com.whut.whw.util.BottomNavigationViewHelper;

import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    /*public static final int FRIENDS = 0;
    public static final int MSG = 1;
    public static final int FIND = 2;
    public static final int RECOMMEND = 3;
    private static final String TAG = "MainActivity";

    private Toolbar toolbar;
    private DrawerLayout mDrawerLayout;
    private ViewPager mViewPager;
    private BottomNavigationView mBottomNavigationView;
    private FloatingActionButton fab;
    private FloatingActionMenu famenu;
    private PopupWindow mPopupWindow;
    private ImageButton mImgBtn_add_word;
    // popupWindow是否显示：true,已经显示；false：未显示
    boolean isShow = false;
    private ImageButton mImgBtn_add_headline;
    // 记录点击bottomNavigationView中的add按钮之前点击的item的ID
    private int preId = -1;
    private ImageView mImg_head;
    private TextView mTv_name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // enable automatic xml icons detection
//        LayoutInflaterCompat.setFactory(getLayoutInflater(), new IconicsLayoutInflater(getDelegate()));
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Set up the toolbar
        toolbar = (Toolbar) findViewById(R.id.tb_main_toolbar);
        setSupportActionBar(toolbar);
        ActionBar ab = getSupportActionBar();
        ab.setHomeAsUpIndicator(R.drawable.ic_menu);
        ab.setDisplayHomeAsUpEnabled(true);

        // 设置抽屉布局的抽屉
        mDrawerLayout = (DrawerLayout) findViewById(R.id.dl_main_drawer);
        mDrawerLayout.setStatusBarBackground(R.color.colorPrimaryDark);
        NavigationView navigationView = (NavigationView) findViewById(R.id.nv_main_navigation);
        if (navigationView != null) {
            setupDrawerContent(navigationView);
        }

        // 设置viewPager
        mViewPager = (ViewPager) findViewById(R.id.vp_main_content);
        setupViewpager(mViewPager);

        // set up bottomNavigation
        mBottomNavigationView = (BottomNavigationView) findViewById(R.id.bnv_main_bottomNav);
        setupBottomNavigationView(mBottomNavigationView);

        // 设置circleFloatingButton
//        setupCircleFloatingBtn();
    }

    *//**
     * 设置抽屉布局的抽屉
     *
     * @param navigationView：抽屉对象（值传递，传递的是对象的地址）
     *//*
    private void setupDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.list_navigation_menu_item:
                        Toast.makeText(MainActivity.this, "清单", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.statistics_navigation_menu_item:
//                        Intent intent =
//                                new Intent(TasksActivity.this, StatisticsActivity.class);
//                        startActivity(intent);
                        Toast.makeText(MainActivity.this, "数据", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
                // Close the navigation drawer when an item is selected.
                mDrawerLayout.closeDrawers();
                return true;
            }
        });
        View headerView=navigationView.getHeaderView(0);
        mImg_head =(ImageView)headerView.findViewById(R.id.img_main_nav_head);
        mImg_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawerLayout.closeDrawers();
                Toast.makeText(MainActivity.this, "head", Toast.LENGTH_SHORT).show();
            }
        });
        mTv_name=(TextView)headerView.findViewById(R.id.tv_main_nav_name);

    }

    private void setupCircleFloatingBtn() {
        int redActionButtonSize = getResources().getDimensionPixelSize(R.dimen.red_action_button_size);
        int redActionButtonMargin = getResources().getDimensionPixelOffset(R.dimen.red_action_button_margin);
        int redActionButtonContentSize = getResources().getDimensionPixelSize(R.dimen.red_action_button_content_size);
        int redActionButtonContentMargin = getResources().getDimensionPixelSize(R.dimen.red_action_button_content_margin);
        int blueSubActionButtonSize = getResources().getDimensionPixelSize(R.dimen.blue_sub_action_button_size);
        int blueSubActionButtonContentMargin = getResources().getDimensionPixelSize(R.dimen.blue_sub_action_button_content_margin);

        // 1,设置FolatingActionButton
        final ImageView fabContent = new ImageView(this);
        fabContent.setImageDrawable(getResources().getDrawable(R.drawable.ic_add));

        // 设置fab中图片的size，margin
        FloatingActionButton.LayoutParams starParams = new FloatingActionButton.LayoutParams(redActionButtonSize, redActionButtonSize);
        starParams.setMargins(redActionButtonMargin,
                redActionButtonMargin,
                redActionButtonMargin,
                redActionButtonMargin);
        fabContent.setLayoutParams(starParams);

        FloatingActionButton.LayoutParams fabIconStarParams = new FloatingActionButton.LayoutParams(redActionButtonContentSize, redActionButtonContentSize);
        fabIconStarParams.setMargins(redActionButtonContentMargin,
                redActionButtonContentMargin,
                redActionButtonContentMargin,
                redActionButtonContentMargin);

        FloatingActionButton darkButton = new FloatingActionButton.Builder(this)
                .setTheme(FloatingActionButton.THEME_DARK)
                .setContentView(fabContent, fabIconStarParams)
                .setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_bottom_center_fab_selector))
                .setPosition(FloatingActionButton.POSITION_BOTTOM_CENTER)
                .setLayoutParams(starParams)
                .build();

        // 设置floatingActionButton的自定义位置


        // 2，设置SubActionButton
        SubActionButton.Builder rLSubBuilder = new SubActionButton.Builder(this)
                .setTheme(SubActionButton.THEME_DARK)
                .setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_bottom_center_fab_action_selector));

        FrameLayout.LayoutParams blueContentParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        blueContentParams.setMargins(blueSubActionButtonContentMargin,
                blueSubActionButtonContentMargin,
                blueSubActionButtonContentMargin,
                blueSubActionButtonContentMargin);
//        rLSubBuilder.setLayoutParams(blueContentParams);
        // Set custom layout params
        FrameLayout.LayoutParams blueParams = new FrameLayout.LayoutParams(blueSubActionButtonSize, blueSubActionButtonSize);
        rLSubBuilder.setLayoutParams(blueParams);

        ImageView rlIcon1 = new ImageView(this);
        ImageView rlIcon2 = new ImageView(this);
        rlIcon1.setImageDrawable(getResources().getDrawable(R.drawable.ic_words_24dp));
        rlIcon2.setImageDrawable(getResources().getDrawable(R.drawable.ic_headline_24dp));

        // Set 2 SubActionButtons
        FloatingActionMenu centerBottomMenu = new FloatingActionMenu.Builder(this)
//                .setAnimationHandler(new SlideInAnimationHandler())
                .addSubActionView(rLSubBuilder.setContentView(rlIcon1, blueContentParams).build())
                .addSubActionView(rLSubBuilder.setContentView(rlIcon2, blueContentParams).build())
                .attachTo(darkButton)
                .setStartAngle(-45)
                .setEndAngle(-135)
                .build();
        centerBottomMenu.setStateChangeListener(new FloatingActionMenu.MenuStateChangeListener() {
            @Override
            public void onMenuOpened(FloatingActionMenu floatingActionMenu) {
                // Rotate the icon of rightLowerButton 45 degrees clockwise
                fabContent.setRotation(0);
                PropertyValuesHolder pvhR = PropertyValuesHolder.ofFloat(View.ROTATION, 45);
                ObjectAnimator animation = ObjectAnimator.ofPropertyValuesHolder(fabContent, pvhR);
                animation.start();
            }

            @Override
            public void onMenuClosed(FloatingActionMenu floatingActionMenu) {
                // Rotate the icon of rightLowerButton 45 degrees counter-clockwise
                fabContent.setRotation(45);
                PropertyValuesHolder pvhR = PropertyValuesHolder.ofFloat(View.ROTATION, 0);
                ObjectAnimator animation = ObjectAnimator.ofPropertyValuesHolder(fabContent, pvhR);
                animation.start();
            }
        });

        rlIcon1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "icon1被点击", Toast.LENGTH_SHORT).show();
            }
        });
    }

    *//**
     * 设置ViewPager不可左右滑动
     * @param mViewPager
     *//*
    private void setupViewpager(ViewPager mViewPager) {
        // 禁止ViewPager滑动
        mViewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        Fragment[] fragments = {BlankFragment.newInstance(), BlankFragment.newInstance(), BlankFragment.newInstance(), BlankFragment.newInstance()};
        String[] titles = {"朋友", "消息", "发现", "推荐"};
        mViewPager.setAdapter(new MyViewpagerAdapter(getSupportFragmentManager(), Arrays.asList(fragments)));
    }


    *//**
     * 设置BottomNavigationView和ViewPager联动
     * @param mBottomNavigationView
     *//*
    private void setupBottomNavigationView(BottomNavigationView mBottomNavigationView) {
        // 设置ShiftingMode=false，使得底部导航栏中各图标可平均分配排列
        BottomNavigationViewHelper.disableShiftMode(mBottomNavigationView);
        mBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.bottom_nav_friends:
                        mViewPager.setCurrentItem(FRIENDS);
                        break;
                    case R.id.bottom_nav_msg:
                        mViewPager.setCurrentItem(MSG);
                        break;
                    case R.id.bottom_nav_add:
                        showToaddDialog();
                        break;
                    case R.id.bottom_nav_find:
                        mViewPager.setCurrentItem(FIND);
                        break;
                    case R.id.bottom_nav_recommend:
                        mViewPager.setCurrentItem(RECOMMEND);
                        break;
                    default:
                        break;
                }
                if (item.getItemId() != R.id.bottom_nav_add) {
                    preId = item.getItemId();
                    Log.e(TAG, "onNavigationItemSelected: " + preId);
                }
                return true;
            }
        });
    }

    *//**
     * 点击点击bottomNavigationView中的add按钮后显示popupWindow
     *//*
    private void showToaddDialog() {
        if (mPopupWindow == null) {
            LayoutInflater inflater = getLayoutInflater().from(this);
            View contentView = inflater.inflate(R.layout.activity_main_addbtn_popwindow, null);
            mImgBtn_add_word = (ImageButton) contentView.findViewById(R.id.imgBtn_main_bottom_word);
            mImgBtn_add_word.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(MainActivity.this, "文字", Toast.LENGTH_SHORT).show();
                    dismissPopupWindow();
                }
            });
            mImgBtn_add_headline = (ImageButton) contentView.findViewById(R.id.imgBtn_main_bottom_headline);
            mImgBtn_add_headline.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(MainActivity.this, "头条", Toast.LENGTH_SHORT).show();
                    dismissPopupWindow();
                }
            });
            contentView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            // 触摸的位置
                            int lastX = (int) event.getRawX();
                            int lastY = (int) event.getRawY();
                            // 点击位置在圆内，将事件分发下去，响应按钮点击事件
                            if (isInCir(mImgBtn_add_word, lastX, lastY) || isInCir(mImgBtn_add_headline, lastX, lastY)) {
                                return false;
                            }
                            break;
                    }
                    dismissPopupWindow();
                    return true;
                }
            });
            mPopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, mViewPager.getHeight());
            ColorDrawable dw = new ColorDrawable(getResources().getColor(R.color.bg_toadd));
            dw.setAlpha(200);
            mPopupWindow.setBackgroundDrawable(dw);
            mPopupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        }
        if (!isShow) {
            showPopupWindow();
        }
    }


    *//**
     * @param btn:圆控件
     * @param lastX:触摸点X坐标
     * @param lastY:触摸点Y坐标
     * @return 得到触摸位置在圆控件内
     *//*
    private boolean isInCir(ImageButton btn, int lastX, int lastY) {
        //获取控件在屏幕的位置
        int[] location = new int[2];
        btn.getLocationOnScreen(location);
        //控件相对于屏幕的x与y坐标
        int x = location[0];
        int y = location[1];
        //圆半径 通过左右坐标计算获得getLeft
        int r = (btn.getRight() - btn.getLeft()) / 2;
        //圆心坐标
        int vCenterX = x + r;
        int vCenterY = y + r;
        //点击位置x坐标与圆心的x坐标的距离
        int distanceX = Math.abs(vCenterX - lastX);
        //点击位置y坐标与圆心的y坐标的距离
        int distanceY = Math.abs(vCenterY - lastY);
        //点击位置与圆心的直线距离
        int distanceZ = (int) Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));
        if (distanceZ <= r)  return true;
        return false;
    }

    *//**
     * 使popupWindow显示
     *//*
    private void showPopupWindow() {
        isShow = true;
        mPopupWindow.showAtLocation(mBottomNavigationView, Gravity.BOTTOM, 0, mBottomNavigationView.getHeight());
        View addView =findViewById(R.id.bottom_nav_add);
        addView.setClickable(false);
    }

    *//**
     * 使popupWindow消失
     *//*
    private void dismissPopupWindow() {
        isShow = false;
        mPopupWindow.dismiss();
//        mBottomNavigationView.setSelectedItemId(preId);
        View addView =findViewById(R.id.bottom_nav_add);
        addView.setClickable(true);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            // 点击Toolbar上的home时，打开抽屉
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
        }
        return super.onOptionsItemSelected(item);
    }

    *//**
     * 处理Activity的onTouch事件
     *
     * @param ev：onTouch事件
     * @return：true/false
     *//*
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int lastX = (int) ev.getRawX();
        int lastY = (int) ev.getRawY();

        View addView = findViewById(R.id.bottom_nav_add);
        int[] location = new int[2];
        addView.getLocationOnScreen(location);
        int x0 = location[0];
        int y0 = location[1];
        int x1 = addView.getRight() - addView.getLeft() + x0;
        int y1 = addView.getBottom() - addView.getTop() + y0;
        if (!((x0 <= lastX && lastX <= x1) && (y0 <= lastY && lastY <= y1))) {
            if (isShow) {
                if (ev.getAction() == MotionEvent.ACTION_UP) {
                    dismissPopupWindow();
//                    return true;
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }*/
}
